<?php
/** 
 * Class Customer
 * 
 */
class Customer {
	var $customer_id = false;
	var $c_name = '';
	var $c_info = '';
	var $c_user = false;
	var $db_fields = array();
	
	function Customer ($id = false) {
		$this->table = TP."_customer";
		
		if(intval($id)) {
			$query="select * from `".$this->table."` where customer_id = $id LIMIT 1";
			$user = $_SESSION['db']->getArray($query);
			
			foreach($user[0] as $k => $v) {
				if(property_exists(get_class($this),$k)) {
					$this->db_fields[] = $k;
					$this->$k = $v;
				}
			}
		}
	}
	
	
  	/**
	 * expects the fields to be updated as an array:
	 * $obj[fields] = array("u_name" => "Charles Bronson"[,...]);
	 */
	function update ($obj) {
		print_r($obj);
		if(is_object($obj)) {
			$set = array();
			foreach($obj as $k => $v) {
				if(property_exists(get_class($this),$k)) {
					$this->$k = $v;
					if(in_array($k,$this->db_fields)) {
						$set[] = "`".$k."` = '".mysql_escape_string($v)."'";
					}
				}
			}
			
			echo $query = "update `".$this->table."` set ".implode($set,", ")." where customer_id = ".$this->customer_id." LIMIT 1";
			$_SESSION['db']->execute($query) or die ($_SESSION['db']->ErrorMsg());
			return true;		
		} else {
			return false;
		}
	}
	
	function create($obj) {
		$error = array();
		if(mysql_escape_string($obj['name']) == '') $error[] = "name";
		
		
		// check if user exists
		if(count($error) == 0) {
			$info = "";
			$name = mysql_real_escape_string($obj->name);
			if(isset($obj->info)) $info = mysql_real_escape_string($obj->info);
			
			$query = "INSERT INTO ".$this->table." SET c_name='$name', u_info='$info'";
			$result = $_SESSION['db']->execute($query) or die ($_SESSION['db']->ErrorMsg());
			
		} else {
			$json = new Services_JSON();
			echo $json->encode(array("error" => $error));
		}
	}
	
	function getData() {
		$return = array();
		$private = array('');
		foreach($this as $e => $v) {
			if(!in_array($e, $private)) {
				$return[$e] = $v;
			}
		}
		return $_SESSION['joel']->plugins_apply('_user_getData',$return);
	}
	
	function getAllData() {
		$return = array();
		foreach($this as $e => $v) {
			$return[$e] = $v;
		}
		return $_SESSION['joel']->plugins_apply('_user_getData',$return[0]);
	}
}